//
//  ViewController.m
//  iOSProjectFramework
//
//  Created by 洪冬介 on 2018/1/24.
//  Copyright © 2018年 洪冬介. All rights reserved.
//

#import "ViewController.h"
#import "DJSectionModel.h"
#import <Photos/Photos.h>

#define sourcePic(s) [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:[NSString stringWithFormat:@"Source.bundle/%@", s]]
#define TOP_MARGIN 15

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) NSMutableArray<DJSectionModel*> *dataScoure;

@end

@implementation ViewController{
    double totalHeight;
}

- (BOOL)prefersStatusBarHidden{
    return YES;
}

- (NSMutableArray<DJSectionModel*> *)dataScoure{
    if (!_dataScoure) {
        _dataScoure = [NSMutableArray array];
    }
    return _dataScoure;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        [self.view addSubview:_tableView];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = WHITE_COLOR;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0.01, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0.01, adaptHeight(10))];
        if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 11.0) {
            _tableView.estimatedSectionHeaderHeight = 10;
            _tableView.estimatedSectionFooterHeight = 0.01;
        }
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.mas_equalTo(0);
            make.height.mas_equalTo(SCREEN_HEIGHT);
        }];
    }
    return _tableView;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.backgroundColor = WHITE_COLOR;

    
    
    totalHeight = 0.0;
    
    NSMutableArray* arr = [NSMutableArray array];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"Source" ofType:@"bundle"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSDirectoryEnumerator *enumerator;
    enumerator = [fileManager enumeratorAtPath:path];
    while((path = [enumerator nextObject]) != nil) {
        [arr addObject:path];
        NSString *imagePath = sourcePic(path);
        UIImage* image = [UIImage imageWithContentsOfFile:imagePath];
        totalHeight += (SCREEN_WIDTH * image.size.height / image.size.width + TOP_MARGIN);
    }
    
    NSMutableArray* mainPics = [NSMutableArray array];//主图
    NSMutableArray* models = [NSMutableArray array];//模特
    NSMutableArray* products = [NSMutableArray array];//示意
    NSMutableArray* fds = [NSMutableArray array];//细节
    NSMutableArray* dps = [NSMutableArray array];//搭配
    
    for (NSString* path in arr) {
        if ([path containsString:@"主图"]) {
            [mainPics addObject:path];
        }else if ([path containsString:@"示意"]){
            [products addObject:path];
        }else if ([path containsString:@"细节"]){
            [fds addObject:path];
        }else if ([path containsString:@"搭配"]){
            [dps addObject:path];
        }else{
            [models addObject:path];
        }
    }
    
    if (mainPics.count) {
        DJSectionModel* sectionModel = [DJSectionModel new];//主图
        sectionModel.title = @"主图";
        sectionModel.items = mainPics;
        [self.dataScoure addObject:sectionModel];
        totalHeight += 100;
    }
    
    if (models.count) {
        DJSectionModel* sectionModel = [DJSectionModel new];//模特
        sectionModel.title = @"模特";
        sectionModel.items = models;
        [self.dataScoure addObject:sectionModel];
        totalHeight += 100;
    }
    
    if (products.count) {
        DJSectionModel* sectionModel = [DJSectionModel new];//示意
        sectionModel.title = @"示意";
        sectionModel.items = products;
        [self.dataScoure addObject:sectionModel];
        totalHeight += 100;
    }

    if (fds.count) {
        DJSectionModel* sectionModel = [DJSectionModel new];//细节
        sectionModel.title = @"细节";
        sectionModel.items = fds;
        [self.dataScoure addObject:sectionModel];
        totalHeight += 100;
    }
    
    if (dps.count) {
        DJSectionModel* sectionModel = [DJSectionModel new];//搭配
        sectionModel.title = @"搭配";
        sectionModel.items = dps;
        [self.dataScoure addObject:sectionModel];
        totalHeight += 100;
    }


    UIImageView *headerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 765/2.0)];
    headerView.image = [UIImage imageNamed:@"NOTIC"];
    totalHeight += headerView.size.height;

    
    self.tableView.tableHeaderView = headerView;
    [self.tableView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(totalHeight + 100);
    }];
//    [self.tableView reloadData];
//    [self.tableView layoutIfNeeded];
//    [self getImage];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataScoure.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    DJSectionModel* sm = self.dataScoure[section];
    return sm.items.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString* path = self.dataScoure[indexPath.section].items[indexPath.row];
    NSString *imagePath = sourcePic(path);
    UIImage* image = [UIImage imageWithContentsOfFile:imagePath];

    UITableViewCell* cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    UIImageView* iv = [[UIImageView alloc] initWithImage:image];
    [cell addSubview:iv];
    [iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.mas_equalTo(0);
        make.bottom.mas_equalTo(-TOP_MARGIN);
    }];
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self getImage];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString* path = self.dataScoure[indexPath.section].items[indexPath.row];
    NSString *imagePath = sourcePic(path);
    UIImage* image = [UIImage imageWithContentsOfFile:imagePath];
    return SCREEN_WIDTH * image.size.height / image.size.width + TOP_MARGIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    DJSectionModel* sectionModel = self.dataScoure[section];
    if ([sectionModel.title containsString:@"主图"]) {
        return 0.01;
    }
    return 100;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    DJSectionModel* sectionModel = self.dataScoure[section];
    if (![sectionModel.title containsString:@"主图"]) {
        UIImageView* iv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:sectionModel.title]];
        iv.contentMode = UIViewContentModeScaleAspectFit;
        return iv;
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (void)getImage{

    UITableView *shadowView = self.tableView;
    // 开启图片上下文
    UIGraphicsBeginImageContextWithOptions(CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT), NO, 2.0f);
    // 保存现在视图的位置偏移信息
    CGPoint saveContentOffset = shadowView.contentOffset;
    // 保存现在视图的frame信息
    CGRect saveFrame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
    // 把要截图的视图偏移量设置为0
    shadowView.contentOffset = CGPointZero;
    // 设置要截图的视图的frame为内容尺寸大小
    shadowView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT);
    //iOS7+ 推荐使用的方法，代替上述方法
     [shadowView drawViewHierarchyInRect:saveFrame afterScreenUpdates:YES];
    // 获取截图
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    // 关闭图片上下文
    UIGraphicsEndImageContext();
    // 将视图的偏移量设置回原来的状态
    shadowView.contentOffset = saveContentOffset;
    // 将视图的frame信息设置回原来的状态
    shadowView.frame = saveFrame;

    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
        [PHAssetChangeRequest creationRequestForAssetFromImage:image];
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        DLog(@"%@",success?@"保存成功":@"保存失败");
    }];

}

@end
